import { _decorator, Button, Component, EditBox, Node } from 'cc';
import { VirtualList } from '../VirtualList';
import { ChatIItem } from './ChatIItem';
const { ccclass, property } = _decorator;

@ccclass('ChatView')
export class ChatView extends Component {
    @property(VirtualList)
    list: VirtualList = null!;

    @property(Button)
    btnSend: Button = null!;

    @property(Button)
    btnEmoji: Button = null!;

    @property(EditBox)
    input: EditBox = null!;

    data: { self: boolean, emoji: string, text: string }[] = [];

    start() {
        this.list.itemRender = this.onItemRender.bind(this);
        this.list.getItemResIndex = this.getItemResIndex.bind(this);
        this.btnSend.node.on("click", this.onSendClick, this);
        this.btnEmoji.node.on("click", this.onClickEmoji, this);
    }

    private onItemRender(index: number, node: Node) {
        let chatInfo = this.data[index];
        node.getComponent(ChatIItem).setData(index, chatInfo);
    }

    private getItemResIndex(index: number) {
        let chatInfo = this.data[index];
        if (chatInfo.self) {
            return chatInfo.emoji ? 2 : 0;
        } else {
            return chatInfo.emoji ? 3 : 1;
        }
    }

    private isSelf = true;
    private onSendClick() {
        let text = this.input.string;
        if (!text) {
            return;
        }
        this.data.push({ self: this.isSelf, text: text, emoji: "" });
        this.list.setData(this.data);
        this.list.scrollToBottom();
        this.input.string = "";
        this.isSelf = !this.isSelf;
    }

    private onClickEmoji() {
        this.data.push({ self: this.isSelf, text: "", emoji: "emoji" });
        this.list.setData(this.data);
        this.list.scrollToBottom();
        this.isSelf = !this.isSelf;
    }
}


